package com.xiaouyudeguang.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.nio.file.FileSystems;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.util.Collection;

/**
 * <p>
 * url工具
 * </p>
 *
 * @author zg
 */
@Slf4j
public class UrlUtils {

    public static final String SLASH = "/";

    /**
     * url匹配
     *
     * @param matchUrls matchUrls
     * @param url       url
     * @return
     */
    public static boolean match(Collection<String> matchUrls, String url) {
        if (matchUrls == null || matchUrls.isEmpty()) {
            return false;
        }
        if (matchUrls.contains(url)) {
            return true;
        }
        for (String matchUrl : matchUrls) {
            if (match(matchUrl, url)) {
                return true;
            }
        }
        return false;
    }

    /**
     * url匹配
     *
     * @param matchUrl matchUrl
     * @param url      url
     * @return
     */
    public static boolean match(String matchUrl, String url) {
        try {
            if (StringUtils.isEmpty(matchUrl) || StringUtils.isEmpty(url)) {
                return false;
            }
            if (!url.startsWith(SLASH)) {
                url = SLASH + url;
            }
            PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:**" + matchUrl);
            return matcher.matches(Paths.get(url));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }


    public static void main(String[] args) {
        System.out.println(match("/match/**","/match/1"));
    }
}
